package com.android.porttallymansystem.ui.activity

import android.Manifest
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.amap.api.location.AMapLocationClient
import com.android.porttallymansystem.PTSApplication
import com.android.porttallymansystem.databinding.ActivityLoginBinding
import com.android.porttallymansystem.logic.Repository
import com.android.porttallymansystem.ui.viewmodel.LoginViewModel
import kotlin.concurrent.thread

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding

    private lateinit var viewModel: LoginViewModel

    private lateinit var prefs: SharedPreferences
    private lateinit var editor: SharedPreferences.Editor

    private val permissions = listOf(
        Manifest.permission.INTERNET,
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.ACCESS_WIFI_STATE,
        Manifest.permission.CHANGE_WIFI_STATE,
        Manifest.permission.ACCESS_BACKGROUND_LOCATION,
        Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
        Manifest.permission.WRITE_SETTINGS,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        prefs = getSharedPreferences("login_information", MODE_PRIVATE)
        editor = prefs.edit()

        hideStatusBar()

        checkPermissions()

        initObserve()

        initData()

        setListener()
    }

    private fun initData() {
        val isRemember = prefs.getBoolean("isRemember", false)
        if (isRemember) {
            binding.cbIsRememberPassword.isChecked = true
            viewModel.setPhoneOrEmail(prefs.getString("phoneOrEmail", "")?:"")
            viewModel.setPassword(prefs.getString("password", "")?:"")
        }
    }

    private fun checkPermissions() {
        val permissionList = ArrayList<String>()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission)
            }
        }
        if (permissionList.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        }
    }

    // 初始化 ViewModel ，并建立观察
    private fun initObserve() {

        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)

        viewModel.phoneOrEmail.observe(this, Observer { phoneOrEmail ->
            binding.etPhoneOrEmail.setText(phoneOrEmail)
        })
        viewModel.password.observe(this, Observer { password ->
            binding.etPassword.setText(password)
        })
    }

    // 设置监听器
    private fun setListener() {
        binding.btLogin.setOnClickListener {
            val phoneOrEmail = binding.etPhoneOrEmail.text.toString()
            val password = binding.etPassword.text.toString()
            if (phoneOrEmail.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "输入不可为空", Toast.LENGTH_SHORT).show()
            } else {
                val phoneRegex = "^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\\d{8}\$"
                val emailRegex = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+\$"
                if (phoneOrEmail.matches(Regex(phoneRegex))) {
                    if (binding.cbIsRememberPassword.isChecked) {
                        editor.putString("phoneOrEmail", phoneOrEmail)
                        editor.putString("password", password)
                        editor.putBoolean("isRemember", true)
                    } else {
                        editor.clear()
                    }
                    editor.apply()
                    thread {
                        val user = Repository.loginCheckByPhone(this, phoneOrEmail, password)
                        if (user != null) {
                            val intent = Intent(this, MainActivity::class.java)
                            startActivity(intent)
                            finish()
                        }
                    }
                } else if (phoneOrEmail.matches(Regex(emailRegex))) {
                    if (binding.cbIsRememberPassword.isChecked) {
                        editor.putString("phoneOrEmail", phoneOrEmail)
                        editor.putString("password", password)
                        editor.putBoolean("isRemember", true)
                    } else {
                        editor.clear()
                    }
                    editor.apply()
                    thread {
                        val user = Repository.loginCheckByEmail(this, phoneOrEmail, password)
                        if (user != null) {
                            val intent = Intent(this, MainActivity::class.java)
                            startActivity(intent)
                            finish()
                        }
                    }
                } else {
                    Toast.makeText(this, "请输入正确的手机号或者电子邮箱地址", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    // 使状态栏透明
    private fun hideStatusBar() {
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        window.statusBarColor = Color.TRANSPARENT
    }
}